const axios = require('axios')
const qs = require('querystring')
const ErrorResult = require('./handle')

let param = qs.stringify({
  grant_type: 'client_credential',
  appid: 'wxc1a99ee9051325df',
  secret: 'f09268d614541e164c11a48dcc4ffc63'
})
// 获取token ,必须有token才能访问腾讯云数据库
let url = 'https://api.weixin.qq.com/cgi-bin/token?' + param
// 云环境ID
let env = 'popop-6gbi6q07b7255a74'
// 数据库插入记录url
let addUrl = 'https://api.weixin.qq.com/tcb/databaseadd?access_token='
// 数据库查询记录url
let queryUrl = 'https://api.weixin.qq.com/tcb/databasequery?access_token='
// 数据库删除记录url
let deleteUrl = 'https://api.weixin.qq.com/tcb/databasedelete?access_token='
// 数据库更新记录url
let updateUrl = 'https://api.weixin.qq.com/tcb/databaseupdate?access_token='

class DataBaseToken {
  constructor() {
    this.token = ''
    this.tokenTime = 0
  }

  getToken() {
    return new Promise((resolve, reject) => {
      if (this.token && Date.now() < this.tokenTime) {
        resolve(this.token)
      } else {
        axios.get(url).then(res => {
          if (res.status === 200) {
            this.token = res.data.access_token
            this.tokenTime = res.data.expires_in * 1000 + Date.now() - 2000
            resolve(this.token)
          } else {
            reject('获取云数据库token失败')
          }
        }).catch(err => {
          reject(err)
        })
      }
    })
  }

  async posteve(dataurl, query) {
    try {
      const token = await this.getToken()
      const data = await axios.post(dataurl + token, {env, query})
      if (data.data.errcode === 0) {
        return data.data
      } else {
        throw new ErrorResult(data.data.errmsg, 400)
      }
    } catch (e) {
      throw new ErrorResult(e, 500)
    }
  }

  update(query) {
    return this.posteve(updateUrl, query)
  }

  query(query) {
    return this.posteve(queryUrl, query)
  }

  delete(query) {
    return this.posteve(deleteUrl, query)
  }

  add(query) {
    return this.posteve(addUrl, query)
  }
}

const databaseToken = new DataBaseToken()
module.exports = {databaseToken}